<!doctype html>
<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Kirikiri SDL2</title>
    <style>
      body {
        font-family: arial;
        width: 100%;
        height: 100%;
        margin-top: 0;
        margin-left: 0;
        overflow: hidden;
        background-color: black;
      }

      .emscripten { padding-right: 0; margin-left: auto; margin-right: auto; display: block;}
      div.emscripten { text-align: center; }      
      div.emscripten_border { border: 1px solid black; }
      /* the canvas *must not* have any border or padding, or mouse coords will be wrong */
      canvas.emscripten { border: 0px none; background-color: black; position:absolute; width: 1280px; height: 720px; left: "0px"; top: "0px"}

      #emscripten_logo {
        display: inline-block;
        margin: 0;
      }

      .spinner {
        height: 30px;
        width: 30px;
        margin: 0;
        margin-top: 20px;
        margin-left: 20px;
        display: inline-block;
        vertical-align: top;

        -webkit-animation: rotation .8s linear infinite;
        -moz-animation: rotation .8s linear infinite;
        -o-animation: rotation .8s linear infinite;
        animation: rotation 0.8s linear infinite;

        border-left: 5px solid rgb(235, 235, 235);
        border-right: 5px solid rgb(235, 235, 235);
        border-bottom: 5px solid rgb(235, 235, 235);
        border-top: 5px solid rgb(120, 120, 120);
        
        border-radius: 100%;
        background-color: rgb(189, 215, 46);
      }

      @-webkit-keyframes rotation {
        from {-webkit-transform: rotate(0deg);}
        to {-webkit-transform: rotate(360deg);}
      }
      @-moz-keyframes rotation {
        from {-moz-transform: rotate(0deg);}
        to {-moz-transform: rotate(360deg);}
      }
      @-o-keyframes rotation {
        from {-o-transform: rotate(0deg);}
        to {-o-transform: rotate(360deg);}
      }
      @keyframes rotation {
        from {transform: rotate(0deg);}
        to {transform: rotate(360deg);}
      }

      #status {
        display: inline-block;
        vertical-align: top;
        margin-top: 30px;
        margin-left: 20px;
        font-weight: bold;
        color: rgb(120, 120, 120);
      }

      #progress {
        height: 20px;
        width: 300px;
      }

      #controls {
        display: inline-block;
        float: right;
        vertical-align: top;
        margin-top: 30px;
        margin-right: 20px;
      }

      #output {
        width: 100%;
        height: 200px;
        margin: 0 auto;
        margin-top: 10px;
        border-left: 0px;
        border-right: 0px;
        padding-left: 0px;
        padding-right: 0px;
        display: block;
        background-color: black;
        color: white;
        font-family: 'Lucida Console', Monaco, monospace;
        outline: none;
      }
    </style>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" id="matherfuckview"/>
    <!--<meta name="page-view-size" content="1280*720">-->
  </head>
  <body>

  <!--<div style="position: absolute; left:0; top:0">-->
    <canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex=-1></canvas>
  <!--</div>-->

    <script type='text/javascript'>
      var statusElement = document.getElementById('status');
      var progressElement = document.getElementById('progress');
      var spinnerElement = document.getElementById('spinner');
      var fuckview = document.getElementById('matherfuckview');
      console.log("http页面加载成功");
      // 根据屏幕像素密度和分辨率，计算拉满全屏的高度时需要的缩放倍率
      try{
        var hw = window.js_tool.getScreenWidth();
        console.log("hw：" + hw);
        var height = parseInt(hw.split("*")[0]);
        console.log("height：" + height);
        var dpr = window.devicePixelRatio;
        console.log("dpr：" + dpr);
        var scale = height/720/dpr;
        console.log("页面缩放比例：" + scale);
        fuckview.setAttribute('content','width=device-width, initial-scale=' + scale);
      }catch(e){
        console.error("初始化像素分辨率失败！！" + e);
        fuckview.setAttribute('content','width=device-width, initial-scale=1.0');
      }


      var Module = {
        arguments: ['/data.xp3'],
        preRun: [],
        postRun: [],
        print: (function() {
          var element = document.getElementById('output');
          if (element) element.value = ''; // clear browser cache
          return function(text) {
            if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
            // These replacements are necessary if you render to raw HTML
            //text = text.replace(/&/g, "&amp;");
            //text = text.replace(/</g, "&lt;");
            //text = text.replace(/>/g, "&gt;");
            //text = text.replace('\n', '<br>', 'g');
            console.log(text);
            if (element) {
              element.value += text + "\n";
              element.scrollTop = element.scrollHeight; // focus on bottom
            }
          };
        })(),
        printErr: function(text) {
          if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
          console.error(text);
        },
        canvas: (function() {
          var canvas = document.getElementById('canvas');

          // As a default initial behavior, pop up an alert when webgl context is lost. To make your
          // application robust, you may want to override this behavior before shipping!
          // See http://www.khronos.org/registry/webgl/specs/latest/1.0/#5.15.2
          canvas.addEventListener("webglcontextlost", function(e) { alert('WebGL context lost. You will need to reload the page.'); e.preventDefault(); }, false);

          return canvas;
        })(),
        setStatus: function(text) {
          if (!Module.setStatus.last) Module.setStatus.last = { time: Date.now(), text: '' };
          if (text === Module.setStatus.last.text) return;
          var m = text.match(/([^(]+)\((\d+(\.\d+)?)\/(\d+)\)/);
          var now = Date.now();
          if (m && now - Module.setStatus.last.time < 30) return; // if this is a progress update, skip it if too soon
          Module.setStatus.last.time = now;
          Module.setStatus.last.text = text;
          if (m) {
            text = m[1];
            //progressElement.value = parseInt(m[2])*100;
            //progressElement.max = parseInt(m[4])*100;
            //progressElement.hidden = false;
            //spinnerElement.hidden = false;
          } else {
            //progressElement.value = null;
            //progressElement.max = null;
            //progressElement.hidden = true;
            //if (!text) spinnerElement.style.display = 'none';
          }
          //statusElement.innerHTML = text;
        },
        totalDependencies: 0,
        monitorRunDependencies: function(left) {
          this.totalDependencies = Math.max(this.totalDependencies, left);
          Module.setStatus(left ? 'Preparing... (' + (this.totalDependencies-left) + '/' + this.totalDependencies + ')' : 'All downloads complete.');
        }
      };
      Module.setStatus('Downloading...');
      window.onerror = function(event) {
        // TODO: do not warn on ok events like simulating an infinite loop or exitStatus
        Module.setStatus('Exception thrown, see JavaScript console');
        //spinnerElement.style.display = 'none';
        Module.setStatus = function(text) {
          if (text) Module.printErr('[post-exception status] ' + text);
        };
      };
    </script>
    <script>
var ASSERTIONS = 1;
/**
 * @license
 * Copyright 2017 The Emscripten Authors
 * SPDX-License-Identifier: MIT
 */

function hasPrefix(str, prefix) {
  return String.prototype.startsWith ?
      str.startsWith(prefix) :
      str.indexOf(prefix) === 0;
}

// Prefix of data URIs emitted by SINGLE_FILE and related options.
var dataURIPrefix = 'data:application/octet-stream;base64,';

// Indicates whether filename is a base64 data URI.
function isDataURI(filename) {
  return hasPrefix(filename, dataURIPrefix);
}

var fileURIPrefix = "file://";

// Indicates whether filename is delivered via file protocol (as opposed to http/https)
function isFileURI(filename) {
  return hasPrefix(filename, fileURIPrefix);
}


// Copied from https://github.com/strophe/strophejs/blob/e06d027/src/polyfills.js#L149

// This code was written by Tyler Akins and has been placed in the
// public domain.  It would be nice if you left this header intact.
// Base64 code from Tyler Akins -- http://rumkin.com

/**
 * Decodes a base64 string.
 * @param {string} input The string to decode.
 */
var decodeBase64 = typeof atob === 'function' ? atob : function (input) {
  var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

  var output = '';
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
  do {
    enc1 = keyStr.indexOf(input.charAt(i++));
    enc2 = keyStr.indexOf(input.charAt(i++));
    enc3 = keyStr.indexOf(input.charAt(i++));
    enc4 = keyStr.indexOf(input.charAt(i++));

    chr1 = (enc1 << 2) | (enc2 >> 4);
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
    chr3 = ((enc3 & 3) << 6) | enc4;

    output = output + String.fromCharCode(chr1);

    if (enc3 !== 64) {
      output = output + String.fromCharCode(chr2);
    }
    if (enc4 !== 64) {
      output = output + String.fromCharCode(chr3);
    }
  } while (i < input.length);
  return output;
};

// Converts a string of base64 into a byte array.
// Throws error on invalid input.
function intArrayFromBase64(s) {
  if (typeof ENVIRONMENT_IS_NODE === 'boolean' && ENVIRONMENT_IS_NODE) {
    var buf;
    try {
      // TODO: Update Node.js externs, Closure does not recognize the following Buffer.from()
      /**@suppress{checkTypes}*/
      buf = Buffer.from(s, 'base64');
    } catch (_) {
      buf = new Buffer(s, 'base64');
    }
    return new Uint8Array(buf['buffer'], buf['byteOffset'], buf['byteLength']);
  }

  try {
    var decoded = decodeBase64(s);
    var bytes = new Uint8Array(decoded.length);
    for (var i = 0 ; i < decoded.length ; ++i) {
      bytes[i] = decoded.charCodeAt(i);
    }
    return bytes;
  } catch (_) {
    throw new Error('Converting base64 string to bytes failed.');
  }
}

// If filename is a base64 data URI, parses and returns data (Buffer on node,
// Uint8Array otherwise). If filename is not a base64 data URI, returns undefined.
function tryParseAsDataURI(filename) {
  if (!isDataURI(filename)) {
    return;
  }

  return intArrayFromBase64(filename.slice(dataURIPrefix.length));
}


/**
 * @license
 * Copyright 2017 The Emscripten Authors
 * SPDX-License-Identifier: MIT
 */

/** @type {function(string, boolean=, number=)} */
function intArrayFromString(stringy, dontAddNull, length) {
  var len = length > 0 ? length : lengthBytesUTF8(stringy)+1;
  var u8array = new Array(len);
  var numBytesWritten = stringToUTF8Array(stringy, u8array, 0, u8array.length);
  if (dontAddNull) u8array.length = numBytesWritten;
  return u8array;
}

function intArrayToString(array) {
  var ret = [];
  for (var i = 0; i < array.length; i++) {
    var chr = array[i];
    if (chr > 0xFF) {
      if (ASSERTIONS) {
        assert(false, 'Character code ' + chr + ' (' + String.fromCharCode(chr) + ')  at offset ' + i + ' not in 0x00-0xFF.');
      }
      chr &= 0xFF;
    }
    ret.push(String.fromCharCode(chr));
  }
  return ret.join('');
}

      // Work-around iframe focus
      // https://github.com/emscripten-core/emscripten/pull/7631
      document.getElementById('canvas').addEventListener('mouseenter', function(e) { window.focus() });
      document.getElementById('canvas').addEventListener('click', function(e) { window.focus() });

      // Work-around chromium autoplay policy
      // https://github.com/emscripten-core/emscripten/issues/6511
      // https://github.com/emscripten-ports/SDL2/pull/104
      function resumeAudio(e) {
          if (typeof Module === 'undefined'
              || typeof Module.SDL2 == 'undefined'
              || typeof Module.SDL2.audioContext == 'undefined')
              return;
          if (Module.SDL2.audioContext.state == 'suspended') {
              Module.SDL2.audioContext.resume();
          }
          if (Module.SDL2.audioContext.state == 'running') {
              document.getElementById('canvas').removeEventListener('click', resumeAudio);
              document.removeEventListener('keydown', resumeAudio);
          }
      }
      document.getElementById('canvas').addEventListener('click', resumeAudio);
      document.addEventListener('keydown', resumeAudio);


          function loadMainJs() {

          var script = document.createElement('script');
          script.src = "krkrsdl2.js";
          document.body.appendChild(script);

          }
          function runWithXP3() {
              _GET = {};
              if (location.search.length > 0) {
                  location.search.substr(1).split('&').forEach(function(item) {
                      _GET[item.split("=")[0]] = item.split("=")[1]
                  });
              }

              var url = "data.xp3";

              if (_GET['data']) {
                  if (_GET['data'].match(/^[0-9a-z._-]+$/i)) {
                      url = _GET['data'];
                  } else {
                      throw "XSS is not allowed";
                  }
              }

              var xhr = new XMLHttpRequest();
              xhr.open('GET', url + ((/\?/).test(url) ? "&" : "?") + (new Date()).getTime(), true);
              xhr.responseType = 'arraybuffer';
              xhr.onprogress = function(event) {
                  var size = -1;
                  if (event.total) size = event.total;
                  if (event.loaded) {
                      if (!xhr.addedTotal) {
                          xhr.addedTotal = true;
                          if (!Module.dataFileDownloads) Module.dataFileDownloads = {};
                          Module.dataFileDownloads[url] = {
                              loaded: event.loaded,
                              total: size
                          };
                      } else {
                          Module.dataFileDownloads[url].loaded = event.loaded;
                      }
                      var total = 0;
                      var loaded = 0;
                      var num = 0;
                      for (var download in Module.dataFileDownloads) {
                          var data = Module.dataFileDownloads[download];
                          total += data.total;
                          loaded += data.loaded;
                          num++;
                      }
                      total = Math.ceil(total * Module.expectedDataFileDownloads / num);
                      if (Module['setStatus']) Module['setStatus']('Downloading project... (' + loaded + '/' + total + ')');
                  } else if (!Module.dataFileDownloads) {
                      if (Module['setStatus']) Module['setStatus']('Downloading project...');
                  }
              };
              xhr.onerror = function(event) {
                  console.log(xhr);
                  console.log(event);
                  Module.print("Cannot download project archive. Please see the JavaScript console for more information.\n");
                  if (Module['setStatus']) Module['setStatus']('Project download error!');
              }
              xhr.onload = function(event) {
                  if (xhr.status == 200 || xhr.status == 304 || xhr.status == 206 || (xhr.status == 0 && xhr.response)) {
                      FS.writeFile('data.xp3', new Uint8Array(xhr.response), {
                          canOwn: true
                      });
                      if (Module['setStatus']) Module['setStatus']('');
                      Module['removeRunDependency']('data.xp3');
                  } else {
                      console.log(xhr);
                      console.log(event);
                      Module.print("Error while downloading project at location " + xhr.responseURL +
                          " : " + xhr.statusText + " (status code " + xhr.status + ")\n");
                      if (Module['setStatus']) Module['setStatus']('Project download error!');
                  }
              };
              xhr.send(null);
              FS.mkdir('/libsdl');
              FS.mkdir('/libsdl/krkrsdl2');
              FS.mount(IDBFS, {}, '/libsdl/krkrsdl2');

              FS.syncfs(true, function (err) {
                Module['removeRunDependency']('savedata');
              });

              Module['addRunDependency']('data.xp3');
              Module['addRunDependency']('savedata');

          }
          Module['preRun'].push(runWithXP3);

          if (!window.WebAssembly) {
            // Current browser does not support WebAssembly, load the .wasm.js JavaScript fallback
            // before the main JS runtime.
            var wasm2js = document.createElement('script');
            wasm2js.src = 'krkrsdl2.wasm.js';
            wasm2js.onload = loadMainJs;
            document.body.appendChild(wasm2js);
          } else {
            // Current browser supports Wasm, proceed with loading the main JS runtime.
            loadMainJs();
          }

</script>
  </body>
</html>


